package org.example.env_boot.service;

import org.example.env_boot.dto.ApiResponse;
import org.example.env_boot.entity.AqiFeedback;
import org.example.env_boot.entity.GridMember;
import org.example.env_boot.entity.Statistics;
import org.example.env_boot.repository.AqiFeedbackRepository;
import org.example.env_boot.repository.GridMemberRepository;
import org.example.env_boot.repository.StatisticsRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 管理员服务类
 */
@Service
public class AdminService {
    
    private final AqiFeedbackRepository feedbackRepository;
    private final GridMemberRepository gridMemberRepository;
    private final StatisticsRepository statisticsRepository;
    
    public AdminService(AqiFeedbackRepository feedbackRepository,
                       GridMemberRepository gridMemberRepository,
                       StatisticsRepository statisticsRepository) {
        this.feedbackRepository = feedbackRepository;
        this.gridMemberRepository = gridMemberRepository;
        this.statisticsRepository = statisticsRepository;
    }
    
    /**
     * 获取所有反馈信息
     */
    public ApiResponse<List<AqiFeedback>> getAllFeedbacks() {
        List<AqiFeedback> feedbacks = feedbackRepository.findAll();
        return ApiResponse.success("获取所有反馈信息成功", feedbacks);
    }
    
    /**
     * 根据状态获取反馈信息
     */
    public ApiResponse<List<AqiFeedback>> getFeedbacksByState(Integer state) {
        List<AqiFeedback> feedbacks = feedbackRepository.findByState(state);
        return ApiResponse.success("获取反馈信息成功", feedbacks);
    }
    
    /**
     * 分配反馈给网格员
     */
    public ApiResponse<AqiFeedback> assignFeedbackToGridMember(Integer feedbackId, Integer gmId) {
        // 验证反馈信息是否存在
        Optional<AqiFeedback> feedbackOpt = feedbackRepository.findById(feedbackId);
        if (feedbackOpt.isEmpty()) {
            return ApiResponse.error("反馈信息不存在");
        }
        
        // 验证网格员是否存在
        Optional<GridMember> gridMemberOpt = gridMemberRepository.findById(gmId);
        if (gridMemberOpt.isEmpty()) {
            return ApiResponse.error("网格员不存在");
        }
        
        AqiFeedback feedback = feedbackOpt.get();
        
        // 检查反馈状态
        if (feedback.getState() != 0) {
            return ApiResponse.error("反馈信息已被处理，无法重新分配");
        }
        
        // 分配给网格员
        feedback.setGmId(gmId);
        feedback.setState(1); // 设置为已指派状态
        
        // 设置指派时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        feedback.setAssignDate(now.format(dateFormatter));
        feedback.setAssignTime(now.format(timeFormatter));
        
        AqiFeedback savedFeedback = feedbackRepository.save(feedback);
        
        return ApiResponse.success("反馈信息分配成功", savedFeedback);
    }
    
    /**
     * 获取系统统计数据
     */
    public ApiResponse<SystemStatistics> getSystemStatistics() {
        // 反馈统计
        Long totalFeedbacks = feedbackRepository.count();
        Long pendingFeedbacks = feedbackRepository.countByState(0);
        Long assignedFeedbacks = feedbackRepository.countByState(1);
        Long confirmedFeedbacks = feedbackRepository.countByState(2);
        
        // 网格员统计
        Long totalGridMembers = gridMemberRepository.count();
        Long activeGridMembers = totalGridMembers; // 暂时设为总数，后续可优化
        
        // 统计数据记录
        Long totalStatistics = statisticsRepository.count();
        
        SystemStatistics statistics = new SystemStatistics();
        statistics.setTotalFeedbacks(totalFeedbacks);
        statistics.setPendingFeedbacks(pendingFeedbacks);
        statistics.setAssignedFeedbacks(assignedFeedbacks);
        statistics.setConfirmedFeedbacks(confirmedFeedbacks);
        statistics.setTotalGridMembers(totalGridMembers);
        statistics.setActiveGridMembers(activeGridMembers);
        statistics.setTotalStatistics(totalStatistics);
        
        return ApiResponse.success("获取系统统计数据成功", statistics);
    }
    
    /**
     * 获取省份和城市的AQI统计
     */
    public ApiResponse<List<Object[]>> getAQIStatisticsByRegion() {
        List<Object[]> provinceStats = statisticsRepository.countByProvinceAndAqiLevel();
        return ApiResponse.success("获取区域AQI统计成功", provinceStats);
    }
    
    /**
     * 获取月度统计数据
     */
    public ApiResponse<List<Object[]>> getMonthlyStatistics() {
        List<Object[]> monthlyStats = statisticsRepository.countByMonth();
        return ApiResponse.success("获取月度统计数据成功", monthlyStats);
    }
    
    /**
     * 获取网格员工作量统计
     */
    public ApiResponse<Map<String, Object>> getGridMemberWorkload() {
        List<GridMember> gridMembers = gridMemberRepository.findAll();
        Map<String, Object> workloadData = new HashMap<>();
        
        for (GridMember gridMember : gridMembers) {
            Long assignedCount = feedbackRepository.countByGmId(gridMember.getGmId());
            Map<String, Object> memberData = new HashMap<>();
            memberData.put("gridMember", gridMember);
            memberData.put("assignedCount", assignedCount);
            workloadData.put(String.valueOf(gridMember.getGmId()), memberData);
        }
        
        return ApiResponse.success("获取网格员工作量统计成功", workloadData);
    }
    
    /**
     * 根据省份和城市查询统计数据
     */
    public ApiResponse<List<Statistics>> getStatisticsByRegion(Integer provinceId, Integer cityId) {
        List<Statistics> statistics;
        
        if (provinceId != null && cityId != null) {
            statistics = statisticsRepository.findByProvinceIdAndCityId(provinceId, cityId);
        } else if (provinceId != null) {
            statistics = statisticsRepository.findByProvinceId(provinceId);
        } else {
            statistics = statisticsRepository.findAll();
        }
        
        return ApiResponse.success("获取统计数据成功", statistics);
    }
    
    /**
     * 根据日期范围查询统计数据
     */
    public ApiResponse<List<Statistics>> getStatisticsByDateRange(String startDate, String endDate) {
        List<Statistics> statistics = statisticsRepository.findByDateRange(startDate, endDate);
        return ApiResponse.success("获取指定日期范围统计数据成功", statistics);
    }
    
    /**
     * 获取可分配的网格员列表
     */
    public ApiResponse<List<GridMember>> getAvailableGridMembers(Integer provinceId, Integer cityId) {
        List<GridMember> gridMembers;
        
        if (provinceId != null && cityId != null) {
            // 查找指定省市的网格员
            gridMembers = gridMemberRepository.findByProvinceIdAndCityId(provinceId, cityId);
        } else {
            // 查找所有网格员
            gridMembers = gridMemberRepository.findAll();
        }
        
        return ApiResponse.success("获取可分配网格员列表成功", gridMembers);
    }
    
    /**
     * 系统统计信息类
     */
    public static class SystemStatistics {
        private Long totalFeedbacks;       // 总反馈数
        private Long pendingFeedbacks;     // 待分配反馈数
        private Long assignedFeedbacks;    // 已分配反馈数
        private Long confirmedFeedbacks;   // 已确认反馈数
        private Long totalGridMembers;     // 总网格员数
        private Long activeGridMembers;    // 活跃网格员数
        private Long totalStatistics;      // 总统计记录数
        
        public Long getTotalFeedbacks() { return totalFeedbacks; }
        public void setTotalFeedbacks(Long totalFeedbacks) { this.totalFeedbacks = totalFeedbacks; }
        public Long getPendingFeedbacks() { return pendingFeedbacks; }
        public void setPendingFeedbacks(Long pendingFeedbacks) { this.pendingFeedbacks = pendingFeedbacks; }
        public Long getAssignedFeedbacks() { return assignedFeedbacks; }
        public void setAssignedFeedbacks(Long assignedFeedbacks) { this.assignedFeedbacks = assignedFeedbacks; }
        public Long getConfirmedFeedbacks() { return confirmedFeedbacks; }
        public void setConfirmedFeedbacks(Long confirmedFeedbacks) { this.confirmedFeedbacks = confirmedFeedbacks; }
        public Long getTotalGridMembers() { return totalGridMembers; }
        public void setTotalGridMembers(Long totalGridMembers) { this.totalGridMembers = totalGridMembers; }
        public Long getActiveGridMembers() { return activeGridMembers; }
        public void setActiveGridMembers(Long activeGridMembers) { this.activeGridMembers = activeGridMembers; }
        public Long getTotalStatistics() { return totalStatistics; }
        public void setTotalStatistics(Long totalStatistics) { this.totalStatistics = totalStatistics; }
    }
} 